<template>
  <div class="app-container">
    <el-button type="primary" size="mini" @click="loadRoot">刷新根节点</el-button>
    <el-button type="success" size="mini" @click="onAddRoot">新增根节点</el-button>

    <!-- 表头模拟 -->
    <div class="tree-table-header">
      <span class="col name">名称</span>
      <span class="col code">编码</span>
      <span class="col level">层级</span>
      <span class="col status">状态</span>
      <span class="col time">创建时间</span>
      <span class="col actions">操作</span>
    </div>

    <!-- 树形表格 -->
    <el-tree
      :data="treeData"
      :props="defaultProps"
      node-key="id"
      :load="loadNode"
      lazy
      highlight-current
      class="region-tree">

      <!-- 自定义节点内容 -->
      <span class="tree-row" slot-scope="{ node, data }">
        <span class="col name">{{ data.regionName }}</span>
        <span class="col code">{{ data.regionCode }}</span>
        <span class="col level">{{ levelMap[data.regionLevel] }}</span>
        <span class="col status">
          <el-switch
            v-model="data.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(data)"
          />
        </span>
        <span class="col time">{{ data.createdAt }}</span>
        <span class="col actions">
          <el-button type="text" size="mini" @click.stop="onAddChild(data)">新增子节点</el-button>
          <el-button type="text" size="mini" @click.stop="onEdit(data)">编辑</el-button>
          <el-button type="text" size="mini" @click.stop="onDelete(data)">删除</el-button>
        </span>
      </span>
    </el-tree>

    <!-- 弹窗：新增/编辑 -->
    <el-dialog :title="formTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="上级区域">
          <span>{{ parentInfoLabel }}</span>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="form.regionName" placeholder="请输入区域名称"/>
        </el-form-item>
        <el-form-item label="编码">
          <el-input v-model="form.regionCode" placeholder="请输入区域编码"/>
        </el-form-item>
        <el-form-item label="层级">
          <el-input-number v-model="form.regionLevel" :min="1" :max="4"/>
          <span style="margin-left: 10px">{{ levelMap[form.regionLevel] }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRegion, getRegion, addRegion, updateRegion, delRegion } from '@/api/system/region'
import request from '@/utils/request'

export default {
  name: 'Region',
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'regionName',
        isLeaf: 'isLeaf'
      },
      dialogVisible: false,
      formTitle: '',
      form: {},
      parentInfoLabel: '',
      // 层级映射
      levelMap: {
        1: '省',
        2: '市',
        3: '区县',
        4: '街道'
      }
    }
  },
  created() {
    this.loadRoot()
  },
  methods: {
    // 加载根节点
    loadRoot() {
      listRegion({}).then(res => {
        this.treeData = (res.data || []).map(item => {
          item.isLeaf = (item.regionLevel >= 4)
          return item
        })
      })
    },
    // 懒加载子节点
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve([])
      }
      listRegion({ parentId: node.data.id }).then(res => {
        const children = (res.data || []).map(it => {
          it.isLeaf = (it.regionLevel >= 4)
          return it
        })
        resolve(children)
      }).catch(() => resolve([]))
    },
    // 状态切换
    handleStatusChange(row) {
      request({
        url: '/system/region/changeStatus',
        method: 'put',
        data: { id: row.id, status: row.status }
      }).then(() => {
        this.$message.success('状态更新成功')
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    // 新增根节点
    onAddRoot() {
      this.formTitle = '新增根节点'
      this.dialogVisible = true
      this.form = {
        parentId: null,
        regionLevel: 1,
        status: 1
      }
      this.parentInfoLabel = '无（根节点）'
    },
    // 新增子节点
    onAddChild(parent) {
      this.formTitle = '新增子节点'
      this.dialogVisible = true
      this.form = {
        parentId: parent.id,
        regionLevel: parent.regionLevel + 1,
        status: 1
      }
      this.parentInfoLabel = `${parent.regionName}（${parent.regionCode}）`
    },
    // 编辑
    onEdit(node) {
      this.formTitle = '编辑节点'
      getRegion(node.id).then(res => {
        this.form = res.data
        this.dialogVisible = true
        this.parentInfoLabel = node.parent ? node.parent.regionName : '无'
      })
    },
    // 保存
    save() {
      if (this.form.id) {
        updateRegion(this.form).then(() => {
          this.$message.success('修改成功')
          this.dialogVisible = false
          this.loadRoot()
        })
      } else {
        addRegion(this.form).then(() => {
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.loadRoot()
        })
      }
    },
    // 删除
    onDelete(node) {
      this.$confirm(
        `将会递归删除【${node.regionName}】及其所有子节点，是否继续？`,
        '二次确认',
        { type: 'warning' }
      ).then(() => {
        delRegion(node.id).then(() => {
          this.$message.success('删除成功')
          this.loadRoot()
        })
      })
    }
  }
}
</script>

<style scoped>
.tree-table-header {
  display: flex;
  padding: 10px;
  font-weight: bold;
  background: #f5f7fa;
}
.tree-row {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 8px 0;
}
.col {
  padding: 0 10px;
  flex: 1;
}
.col.name { flex: 2; }
.col.code { flex: 1; }
.col.level { flex: 1; }
.col.status { flex: 1; }
.col.time { flex: 2; }
.col.actions { flex: 2; text-align: left; }
</style>
